import React, { Fragment, useContext, useEffect, useState } from 'react';
import Chart from './component/Chart.jsx';
import styles from './Statistics.scss';
import AppContext from '../../context';
import { getTravelDays } from './api';
import LoadingToast from '../../UIComponent/LoadingToast.jsx';
import './mock';

export default function Statistics(props) {
    const app = useContext(AppContext);
    const defaultDepartmentName = app.statistics.departmentName.length > 0 ? app.statistics.departmentName : [{
        name: '全部',
        index: 0,
        disable: true
    }];
    const [departmentName, setDepartmentName] = useState(defaultDepartmentName);
    const [data, setData] = useState({ list: { org: [], person: [] } });
    const [orgId, setOrgId] = useState(app.statistics.orgid);
    const [parentOrgId, setParentOrgId] = useState('');
    const [date, setDate] = useState(getDate());
    const [isLoading, setLoading] = useState(false);
    function getDate() {
        const _date = new Date();
        const year = _date.getFullYear();
        const month = _date.getMonth() + 1;
        return `${year}-${month < 10 ? `0${month}` : month}`;
    }
    useEffect(() => {
        getTravelDays({ org_id: orgId, company_id: app.user.company_id, date })
            .then(result => {
                const allChildOrg = result.data;
                const travelDay = getTravelDayData(allChildOrg);
                setData(travelDay);
            })
    }, []);
    function getTravelDayData(travelDay) {
        const allChildOrg = _.get(travelDay, ['list', 'org']);
        if (allChildOrg) {
            if (_.get(travelDay, ['list', 'org'])) {
                _.set(travelDay, ['list', 'org'], allChildOrg);
                return travelDay;
            }
        } else {
            return travelDay;
        }
    }
    function onChangeDate(e) {
        setDate(e.target.value);
        getTravelDays({ org_id: orgId || '', company_id: app.user.company_id, date: e.target.value }).then(result => {
            const _result = _.cloneDeep(result);
            setData(_result.data);
        });
    }
    function onClickOrg(item) {
        setLoading(true);
        const _departmentName = _.cloneDeep(departmentName);
        _.unset(_departmentName, [_departmentName.length - 1, 'disable']);
        setDepartmentName([
            ..._departmentName, {
                name: item.org_name,
                parent_id: parentOrgId,
                id: item.org_id,
                disable: true,
                index: departmentName.length
            }
        ]);
        setOrgId(item.org_id);
        setParentOrgId(item.org_id);
        getTravelDays({ org_id: item.org_id || '', company_id: app.user.company_id, date }).then(result => {
            const _result = _.cloneDeep(result);
            const travelDay = getTravelDayData(_result.data);
            setData(travelDay);
            setLoading(false);
        });
    }
    function onClickDepartment(department) {
        setLoading(true);
        getTravelDays({ org_id: department.id || '', company_id: app.user.company_id, date }).then(result => {
            const _departmentName = _.cloneDeep(departmentName);
            const travelDay = getTravelDayData(result.data);
            setData(travelDay);
            _.remove(_departmentName, ((it, index) => {
                return index >= department.index + 1;
            }));
            _.update(_departmentName, [department.index], (it) => {
                return {
                    ...it,
                    disable: true
                }
            });
            setDepartmentName(_departmentName);
            setParentOrgId(department.parent_id);
            setLoading(false);
        });
    }

    // 渲染组织
    const renderOrigin = () => {
        const list = _.get(data.list, ['org']) || _.get(data, ['list']);
        return (
            <div className={styles.box}>
                <div className={`${styles.table_head} weui-flex`}>
                    <div className={`${styles.li}`}>
                        <div className="placeholder">分组</div>
                    </div>
                    <div className={`${styles.li}`}>
                        <div className="placeholder">人数</div>
                    </div>
                    <div className={`${styles.li}`}>
                        <div className="placeholder">人均</div>
                    </div>
                    <div className={`${styles.li}`}>
                        <div className="placeholder">贡献</div>
                    </div>
                </div>
                <div>
                    {list.map((item) => (
                        <div className={`${styles.table_body} weui-flex`} key={item.org_id} onClick={() => onClickOrg(item)}>
                            <div className={`${styles.li}`}>
                                <div className={styles.li_head}>{_.get(item, ['org_name']) && _.get(item, ['org_name']).substring(0, 2)}</div>
                                <div className={`${styles.li_name} placeholder`}>{item.org_name}</div>
                            </div>
                            <div className={`${styles.li}`}>
                                <div className={`placeholder ${styles.p}`}>{item.actual_count || 0}/{item.count}</div>
                            </div>
                            <div className={`${styles.li}`}>
                                <div className={`placeholder ${styles.p}`}>{Number(item.actual_average).toFixed(1) || 0}天</div>
                            </div>
                            <div className={`${styles.li}`}>
                                <div className={`placeholder ${styles.p}`}>{item.note || 0}</div>
                            </div>
                            <div className={`${styles.li}`}>
                                <div className={`placeholder ${styles.p}`}>{item.score || 0}</div>
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        )
    };
    // 成员统计
    const renderMember = () => {
        const list = _.get(data.list, ['person']) || _.get(data, ['list']);
        return (
            <div className={styles.box}>
                <div className={`${styles.table_head} weui-flex`}>
                    <div className={`${styles.li}`} style={{ flex: 2 }}>
                        <div className="placeholder">分组</div>
                    </div>
                    <div className={`${styles.li}`}>
                        <div className="placeholder">天数</div>
                    </div>
                    <div className={`${styles.li}`}>
                        <div className="placeholder">贡献</div>
                    </div>
                </div>
                <div>
                    {list.map((item, index) => (
                        <div className={`${styles.table_body} weui-flex`} key={`person_${index}`}>
                            <div className={`${styles.li}`} style={{ flex: 2 }}>
                                <div className={styles.li_head}>{item.user_name.substring(1, 3)}</div>
                                <div className={`${styles.li_name}placeholder`}>{item.user_name}</div>
                            </div>
                            <div className={`${styles.li}`}>
                                <div className="placeholder">{item.actual_count}/{item.plan_count}</div>
                            </div>
                            <div className={`${styles.li}`}>
                                <div className="placeholder">{item.score}</div>
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        )
    };
    return (
        <Fragment>
            {isLoading && <LoadingToast />}
            <div className={styles.bread_crumb}>
                {departmentName.map((department, index) => {
                    return (
                        <div key={index + 1} className={styles.dep_name_cell}>
                            <div className={styles.department_name} style={{ color: _.get(department, ['disable']) ? '#847f7f' : '' }} onClick={() => onClickDepartment(department)}>
                                {index > 0 && <i className='iconfont icon_arrow' />}
                                {department.name}
                            </div>
                        </div>)
                })}
            </div>
            <div className={styles.container}>
                <div className={styles.box}>
                    <div className={styles.input_box}>
                        <input type="month" value={date} onChange={(e) => onChangeDate(e)} />
                    </div>
                    <Chart data={data} />
                </div>
                {((Array.isArray(data.list) && data.is_org) || _.get(data.list, ['org', 'length']) > 0) && renderOrigin()}
                {((Array.isArray(data.list) && !data.is_org) || _.get(data.list, ['person', 'length']) > 0) && renderMember()}
            </div>
        </Fragment>
    )
}
